package cn.tedu.simulateioc;/**
 * @Author 金帮嘉诚 @Date 2021-07-16 星期五 18:54
 */
/*本类用于测试*/

import sun.awt.image.ImageWatched;

import javax.jws.Oneway;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 知识点
 */
public class MyIoC {
    private List<Bean> beanFactory = new ArrayList<>();

    //创建该对象时 会同时创建 一些不同类的对象
    public MyIoC() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        Bean bean1 = new Bean("hello", "cn.tedu.simulateioc.Hello");
        Bean bean2 = new Bean("user", "cn.tedu.simulateioc.User");
        Bean bean3 = new Bean("sun", "cn.tedu.simulateioc.Sun");

        beanFactory.add(bean1);
        beanFactory.add(bean2);
        beanFactory.add(bean3);
        init();
    }

    //写成成员变量方便被另一个方法getBean调用
    private final Map<String, Object> factoryBeanObject = new ConcurrentHashMap<>();

    //这个方法是为了将 id名和类对象的对应关系建立起来，以实现根据id名获取对象
    private void init() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        for (Bean b : beanFactory
        ) {
            String key = b.getBeanName();
            String path = b.getBeanPath();
            Object value = Class.forName(path).newInstance();
//            System.out.println(factoryBeanObject);//{}
            factoryBeanObject.put(key, value);
        }
    }

    public Object getBean(String beanName){
        return factoryBeanObject.get(beanName);
    }

}
